package cn.actoncode.boot.framework.common.http.okhttp;

import cn.actoncode.boot.framework.common.exception.PlatformError;
import cn.actoncode.boot.framework.common.exception.ServiceErrorException;
import cn.actoncode.boot.framework.common.http.MediaUploadRequestExecutor;
import cn.actoncode.boot.framework.common.http.RequestHttp;
import cn.actoncode.boot.framework.common.http.enums.PlatformType;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 *
 * @author bin
 */
public class OkHttpMediaUploadRequestExecutor extends MediaUploadRequestExecutor<OkHttpClient, OkHttpProxyInfo> {
    public OkHttpMediaUploadRequestExecutor(RequestHttp requestHttp) {
        super(requestHttp);
    }

    @Override
    public String execute(String uri, Map<String, String> headers, File file, PlatformType platformType) throws ServiceErrorException, IOException {

        RequestBody body = new MultipartBody.Builder()
                .setType(MediaType.parse("multipart/form-data"))
                .addFormDataPart("media",
                        file.getName(),
                        RequestBody.Companion.create(file, MediaType.parse("application/octet-stream")))
                .build();
        Request request = new Request.Builder().url(uri).post(body).build();

        Response response = requestHttp.getRequestHttpClient().newCall(request).execute();
        String responseContent = response.body().string();

        PlatformError error = PlatformError.parse(responseContent, platformType);
        if (error.getErrorCode() != platformType.getCode()) {
            throw new ServiceErrorException(error);
        }
        return responseContent;
    }

}
